package com.jake.xpage.scheme;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.jake.xpage.page.XPageArgument;
import com.jake.xpage.router.XPageRoute;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 用于创建和解析module
 */
public class XPageSchemeUrlGenerator {
    private static String sScheme = "native";

    /**
     * 如果要替换scheme 需要在创建拦截器之前设置
     *
     * @param scheme
     */
    public static void setScheme(String scheme) {
        sScheme = scheme;
    }

    public static String getScheme() {
        return sScheme;
    }

    public static String generateNativeUrl(String module, String path) {
        return sScheme + "://" + module + path;
    }

    public static String parseModule(String url) {
        return parseModule(url, null);
    }

    public static String parseModule(String url, String defaultValue) {
        if (!TextUtils.isEmpty(url) && url.startsWith(sScheme)) {
            Uri uri = Uri.parse(url);
            String module = uri.getHost();
            if (!TextUtils.isEmpty(module)) {
                return module;
            }
        }
        return defaultValue;
    }

    @Nullable
    public static XPageRoute parseUrl(String url) {
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            String query = uri.getQuery();
            String nativeUrl = url;
            boolean hasQuery = !TextUtils.isEmpty(query);
            if (hasQuery) {
                nativeUrl = url.substring(0, url.indexOf("?"));
            }
            XPageRoute route = XPageRoute.obtain(parseModule(url), nativeUrl);
            if (!TextUtils.isEmpty(query)) {
                Bundle params = parseQueryString(uri.getQuery());
                if (!params.isEmpty()) {
                    XPageArgument argument = new XPageArgument();
                    argument.bundle.putAll(params);
                    route.setArgument(argument);
                }
            }
            return route;
        }
        return null;
    }

    public static Bundle parseQueryString(String queryString) {
        Bundle queryPairs = new Bundle();
        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            String key = pair.substring(0, idx);
            String value = pair.substring(idx + 1);
            try {
                queryPairs.putString(URLDecoder.decode(key, "UTF-8"),
                        URLDecoder.decode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                queryPairs.putString(key, value);
            }
        }
        return queryPairs;
    }
}
